<?php

class Ead_RepositorioController extends App_Controller_Action
{
    public $dir = 'public/upload/repositorio/';
    
    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_list.js');
        
        $search = $this->_getParam('inp-search', '');
        $this->view->search = $search;
        $where = 'REP_STA = "1"';
        if(strlen($search) > 1){
            $where .= ' AND REP_NOM like "%'.$search.'%"';
        }

        $TIP_ID = $this->_getParam('TIP_ID', 0);
        if($TIP_ID > 0) $where .= ' and TIP_ID = '.$TIP_ID;
        
        $obj = new Ead_Model_DbTable_Repositorio();
        $result = $obj->fetchAll($obj->select()->where($where)->order(array('REP_NOM ASC','REP_PRTNUM ASC')));
        $this->view->result = $this->paginacao($result);
    }
    
    
    public function editAction() {
        
        $form = new Ead_Form_Repositorio();
        $form->submit->setLabel('Gravar');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_geral.js');
        
        Zend_Loader::loadClass('imagem','library');
        
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if ($form->isValid($formData)) {
                    $id = (int) $form->getValue('REP_ID');
                    if($id > 0 && is_uploaded_file($_FILES['REP_FILE'])){
                        imagem::delete($this->getNomeArquivo($id),$this->dir);
                    }
                    $returnImg = imagem::upload('REP_FILE',$this->dir,$id);

                    $datahora = date('Y-m-d H:i:00'); // 0000-00-00 00:00:00
                    $data = $form->getValues();
                    $data['REP_EXT'] = $returnImg['ext'];
                    unset($data['REP_FILE']);
                    unset($data['img']);
                    
                    $obj = new Ead_Model_DbTable_Repositorio();

                    if($data['REP_PRTQTD'] <= 0) $data['REP_PRTQTD'] = 1;
                    if($data['REP_PRTNUM'] <= 0) $data['REP_PRTNUM'] = 1;

                    if ($id == 0){
                        $data['REP_DATHOR'] = $datahora;

                        $obj->insert($data);

                        if(strlen($returnImg['filenew']) > 0){
                            $id =  $obj->getAdapter()->lastInsertId();                    
                            $_id = imagem::formatNomeArquivo($id,$datahora);

                            imagem::rename($_id,$this->dir,$returnImg['filenew']);
                            
                            chmod($this->dir.$_id.'.'.end(explode('.', $returnImg['filenew'])), 0644);
                        }
                    }
                    else{
                        $obj->update($data, 'REP_ID = ' . $id);

                        if(strlen($returnImg['filenew']) > 0){
                            $_id = $this->getNomeArquivo($id);

                            imagem::rename($_id,$this->dir,$returnImg['filenew']);
                            
                            chmod($this->dir.$_id.'.'.end(explode('.', $returnImg['filenew'])), 0644);
                        }
                    }
                   $this->_helper->redirector('index');
                } else {
                    $form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $form->populate($formData);
            }  
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $obj = new Ead_Model_DbTable_Repositorio();
                $form->populate($obj->fetchRow('REP_ID = ' . $id)->toArray());
            }
        }
    }

    public function deleteAction() {
        Zend_Loader::loadClass('imagem','library');
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE; 
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            imagem::delete($this->getNomeArquivo($id),$this->dir);
            
            $data = array('REP_STA'=>0);
            
            $obj = new Ead_Model_DbTable_Repositorio();
            $ok = (bool) $obj->update($data,'REP_ID = '.(int)$id);
            //$ok = (bool) $obj->delete('REP_ID = '.(int)$id);
            
            //$this->_helper->redirector('index'); 
        } else {
            //$id = $this->_getParam('id', 0);
            //$obj = new Ead_Model_DbTable_Repositorio();
            //$form->populate($obj->fetchRow('REP_ID = ' . $id)->toArray());
        }
        
        echo json_encode(array('ok' => $ok));
    }
    
    public function getNomeArquivo($id) {
        Zend_Loader::loadClass('imagem','library');
        
        $obj = new Ead_Model_DbTable_Repositorio();
        $res = $obj->fetchRow('REP_ID = '.(int)$id);
        
        return  imagem::formatNomeArquivo($res->REP_ID,$res->REP_DATHOR);
    }
    
    public function findAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
       
        $q = strtolower($this->_getParam('term'));
        
        $index = array();
        $result = array();
        $where = 'REP_STA = 1 and REP_NOM like "'.$q.'%"';
        
        if($this->_getParam('tipmat') > 0)
            $where .= ' and TIP_ID = '.$this->_getParam('tipmat');
        
        $obj = new Ead_Model_DbTable_Repositorio();
        $rows = $obj->fetchAll($obj->select()->where($where)->order(array('REP_NOM ASC','REP_PRTNUM ASC')));
        foreach ($rows as $res) {
            if(strpos(strtolower($res->REP_NOM), $q) !== false && array_search($res->REP_NOM, $index) === false) {
                array_push($result, array("id"=>$res->REP_ID,"label"=>$res->REP_NOM,"value" => $res->REP_NOM));
                $index[] = $res->REP_NOM; 
            }
            if(count($result) > 20) break;
        }

        echo json_encode($result);
    }
    
    public function arquivoAction(){
        $this->_helper->layout->disableLayout(); 
        
        $search = $this->_getParam('inp-search', '');
        $this->view->search = $search;
        $where = 'REP_STA = 1 and REP_ID > 0';
        if(strlen($search) > 1){
            $where = 'REP_NOM like "%'.$search.'%"';
        }
       
        $TIP_ID = $this->_getParam('TIP_ID', 0);
        if($TIP_ID > 0) $where .= ' and TIP_ID = '.$TIP_ID;
        
        if($this->_getParam('tipmat') > 0){
            $where .= ' and TIP_ID = '.$this->_getParam('tipmat');
            $this->view->headScript()->appendScript('var tipmat = '.$this->_getParam('tipmat').' ;');
        }
        
        $obj = new Ead_Model_DbTable_Repositorio();
        $result = $obj->fetchAll($obj->select()->where($where)->order(array('REP_NOM ASC','REP_PRTNUM ASC')));
        $this->view->result = $this->paginacao($result,10);
        
    }
    public function testeAction(){
        
    }
}

